package com.bf.electroplating.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.bf.electroplating.pojo.entity.*;
import com.bf.electroplating.pojo.vo.DeviceRelationVO;
import com.bf.electroplating.service.*;
import com.bf.electroplating.util.HttpUtil;
import com.bf.electroplating.util.SignUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 企业数据同步服务实现类
 * 
 * @author gzd
 * @since 2025-09-22
 */
@Slf4j
@Service
public class CompanyDataSyncServiceImpl implements ICompanyDataSyncService {

    @Autowired
    private ComCompanyService comCompanyService;

    @Autowired
    private ICompanyDeviceService companyDeviceService;

    @Autowired
    private ICompanyDeviceStatusService companyDeviceStatusService;

    @Autowired
    private ComWorkshopService comWorkshopService;

    @Autowired
    private IWorkshopMonitoringPointService workshopMonitoringPointService;

    @Value("${company.api.baseUrl:https://tem.jjzn21.com/vodka}")
    private String apiBaseUrl;

    @Value("${company.api.secret:bcc2b6db2fd54ca08d35414145713f13}")
    private String apiSecret;
    @Resource
    private ComExtraWorkshopService comExtraWorkshopService;

    @Autowired
    private ICompanyDeviceRelationService companyDeviceRelationService;
//    private IDeviceDataService iDeviceDataService;

    @Override
    public void syncCompanyList() {
        try {
            log.info("开始同步企业列表数据");
            
            // 调用第三方平台企业列表接口
            String url = apiBaseUrl + "/out/company/list";
            JSONObject requestBody = new JSONObject();
            // 6.1接口无需参数
            String response = HttpUtil.post(url, SignUtil.generateParams(requestBody));
            
            if (StringUtils.hasText(response)) {
                JSONObject result = JSON.parseObject(response);
                if (result.getBoolean("success")) {
                    List<JSONObject> companyList = result.getJSONArray("data").toJavaList(JSONObject.class);
                    
                    log.info("获取到第三方平台企业数据，共{}条", companyList.size());
                    
                    // 遍历第三方平台企业数据
                    for (JSONObject platformCompany : companyList) {
                        String platformId = platformCompany.getString("id");
                        String platformEnterpriseName = platformCompany.getString("enterpriseName");
                        
                        if (StringUtils.hasText(platformId) && StringUtils.hasText(platformEnterpriseName)) {
                            // 根据企业名称匹配本地企业
                            ComCompany localCompany = findCompanyByName(platformEnterpriseName);
                            
                            if (localCompany != null) {
                                // 更新本地企业的第三方平台ID
                                updateCompanyPlatformId(localCompany, platformId);
                                log.info("匹配成功：本地企业[{}] -> 第三方平台ID[{}]", 
                                        platformEnterpriseName, platformId);
                            } else {
                                log.warn("未找到匹配的本地企业：{}", platformEnterpriseName);
                            }
                        } else {
                            log.warn("第三方平台企业数据不完整：ID={}, 名称={}", platformId, platformEnterpriseName);
                        }
                    }
                    
                    log.info("企业列表数据同步完成，共处理{}条数据", companyList.size());
                } else {
                    log.error("获取第三方平台企业列表失败：{}", result.getString("message"));
                }
            } else {
                log.error("调用第三方平台企业列表接口无响应");
            }
        } catch (Exception e) {
            log.error("同步企业列表数据异常", e);
        }
    }

    @Override
    public void syncCompanyDeviceList(String companyId, String id, ComCompany company) {
        try {
            log.info("开始同步企业设备列表数据，企业ID：{}", companyId);
            
            // 调用企业设备列表接口
            String url = apiBaseUrl + "/out/company/device/list";
            JSONObject requestBody = new JSONObject();
            requestBody.put("id", Integer.parseInt(companyId));
            String response = HttpUtil.post(url, SignUtil.generateParams(requestBody));
            if (StringUtils.hasText(response)) {
                JSONObject result = JSON.parseObject(response);
                if (result.getBoolean("success")) {
                    List<JSONObject> regionList = result.getJSONArray("data").toJavaList(JSONObject.class);
                    
                    for (JSONObject regionData : regionList) {
                        List<JSONObject> enterpriseList = regionData.getJSONArray("enterprises").toJavaList(JSONObject.class);
                        
                        for (JSONObject enterpriseData : enterpriseList) {
                            String enterpriseId = enterpriseData.getString("enterpriseId");
                            String enterpriseName = enterpriseData.getString("enterpriseName");
                            List<JSONObject> workshopList = enterpriseData.getJSONArray("workshops").toJavaList(JSONObject.class);
                            
                            for (JSONObject workshopData : workshopList) {
                                String workshopName = workshopData.getString("workshopName");
                                // 根据车间名称匹配车间
                                ComExtraWorkshop matchedWorkshop = findWorkshopByName(workshopName, id);
                                //todo 此处要入库
                                if (matchedWorkshop == null) {
                                    matchedWorkshop = new ComExtraWorkshop();
                                    matchedWorkshop.setCompanyId(company.getId());
                                    matchedWorkshop.setWorkshopName(workshopName);
                                    matchedWorkshop.setParkId("1001");
                                }
                                saveOrUpdateWorkShop(company,matchedWorkshop);
                                List<JSONObject> monitoringPointList = workshopData.getJSONArray("monitoringPoints").toJavaList(JSONObject.class);
                                for (JSONObject monitoringPointData : monitoringPointList) {
                                    // 保存或更新监控点数据，获取监控点ID
                                    String monitoringPointId = saveOrUpdateMonitoringPoint(monitoringPointData, matchedWorkshop, enterpriseName);
                                    
                                    List<JSONObject> deviceList = monitoringPointData.getJSONArray("devices").toJavaList(JSONObject.class);
                                    
                                    for (JSONObject deviceData : deviceList) {
                                        saveOrUpdateCompanyDevice(deviceData, enterpriseData, workshopData, monitoringPointData, matchedWorkshop, monitoringPointId);
                                    }
                                }
                            }
                        }
                    }
                    
                    // 同步设备关联数据
                    syncCompanyDeviceRelations(companyId);
                    
                    log.info("企业设备列表数据同步完成，企业ID：{}", companyId);
                } else {
                    log.error("企业设备列表数据同步失败：{}", result.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("同步企业设备列表数据异常，企业ID：{}", companyId, e);
        }
    }

    private void saveOrUpdateWorkShop(ComCompany company, ComExtraWorkshop matchedWorkshop) {
        try {

            ComExtraWorkshop comExtraWorkshop = matchedWorkshop;
            comExtraWorkshop.setCompanyId(company.getId());
            comExtraWorkshop.setParkId(company.getParkId());
            comExtraWorkshop.setDelFlag("0");

            // 检查监控点是否已存在
            ComExtraWorkshop existingPoint = comExtraWorkshopService.lambdaQuery()
                    .eq(ComExtraWorkshop::getWorkshopName, comExtraWorkshop.getWorkshopName())
                    .eq(ComExtraWorkshop::getCompanyId, company.getId())
                    .one();

            if (existingPoint == null) {
                comExtraWorkshopService.save(comExtraWorkshop);
                log.info("新增车间：{}", comExtraWorkshop);
            } else {
                comExtraWorkshopService.updateById(existingPoint);
                log.info("更新车间：{}", existingPoint);
            }
        } catch (Exception e) {
            log.error("更新车间异常", e);
        }
    }

    @Override
    public void syncCompanyDeviceStatus(String deviceId, String curDate) {
        try {
            log.info("开始同步企业设备状态数据，设备ID：{}，日期：{}", deviceId, curDate);
            
            // 调用企业设备状态接口
            String url = apiBaseUrl + "/out/electricity/char";
            JSONObject requestBody = new JSONObject();
            requestBody.put("deviceId", Integer.parseInt(deviceId));
            requestBody.put("curDate", curDate);
            String response = HttpUtil.post(url, SignUtil.generateParams(requestBody));
            
            if (StringUtils.hasText(response)) {
                JSONObject result = JSON.parseObject(response);
                if (result.getBoolean("success")) {
                    JSONObject data = result.getJSONObject("data");
                    if (data != null) {
                        // 保存设备状态数据
                        saveCompanyDeviceStatus(data, deviceId);
                        
                        // 保存设备数据记录
                        saveDeviceData(data, deviceId);
                    }
                    
                    log.info("企业设备状态数据同步完成，设备ID：{}", deviceId);
                } else {
                    log.error("企业设备状态数据同步失败：{}", result.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("同步企业设备状态数据异常，设备ID：{}", deviceId, e);
        }
    }

    @Override
    public void syncCompanyDeviceRelations(String enterpriseId) {
        try {
            log.info("开始同步企业设备关联数据，企业ID：{}", enterpriseId);
            
            // 调用6.11设备关联接口
            String url = apiBaseUrl + "/out/point/location/list";
            JSONObject requestBody = new JSONObject();
            requestBody.put("enterpriseId", Integer.parseInt(enterpriseId));
            String response = HttpUtil.post(url, SignUtil.generateParams(requestBody));
            
            if (StringUtils.hasText(response)) {
                JSONObject result = JSON.parseObject(response);
                if (result.getBoolean("success")) {
                    List<JSONObject> relationList = result.getJSONArray("data").toJavaList(JSONObject.class);
                    
                    // 转换为VO对象
                    List<DeviceRelationVO> deviceRelations = new ArrayList<>();
                    for (JSONObject relationData : relationList) {
                        DeviceRelationVO deviceRelation = convertToDeviceRelationVO(relationData);
                        deviceRelations.add(deviceRelation);
                    }
                    
                    // 保存设备关联数据
                    companyDeviceRelationService.syncDeviceRelations(enterpriseId, deviceRelations);
                    
                    log.info("企业设备关联数据同步完成，企业ID：{}，关联数据：{}条", enterpriseId, deviceRelations.size());
                } else {
                    log.error("企业设备关联数据同步失败：{}", result.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("同步企业设备关联数据异常，企业ID：{}", enterpriseId, e);
        }
    }

    @Override
    public void syncAllCompanyData() {
        try {

            log.info("开始同步所有企业数据");

            // 1. 同步企业列表
            syncCompanyList();
            // 2. 获取所有企业ID，同步设备列表
            List<ComCompany> companyList = comCompanyService.list();
            for (ComCompany company : companyList) {
                if (StringUtils.hasText(company.getExtraPlatformId())) {
                    syncCompanyDeviceList(company.getExtraPlatformId(),company.getId(),company);
                }
            }

            // 3. 获取所有设备ID，同步设备状态
            List<CompanyDevice> deviceList = companyDeviceService.list();
            String currentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            for (CompanyDevice device : deviceList) {
                syncCompanyDeviceStatus(device.getId(), currentDate);
            }

            log.info("所有企业数据同步完成");
        } catch (Exception e) {
            log.error("同步所有企业数据异常", e);
        }
    }


    /**
     * 根据车间名称查找车间
     */
    private ComExtraWorkshop findWorkshopByName(String workshopName, String enterpriseId) {
        try {
            // 根据车间名称和企业ID查找车间
            return comExtraWorkshopService.lambdaQuery()
                    .eq(ComExtraWorkshop::getWorkshopName, workshopName)
                    .eq(ComExtraWorkshop::getCompanyId, enterpriseId)
                    .one();
        } catch (Exception e) {
            log.error("查找车间异常，车间名称：{}，企业ID：{}", workshopName, enterpriseId, e);
            return null;
        }
    }

    /**
     * 保存或更新监控点信息
     * @return 监控点ID
     */
    private String saveOrUpdateMonitoringPoint(JSONObject monitoringPointData, ComExtraWorkshop workshop, String enterpriseName) {
        try {
            String monitoringPointName = monitoringPointData.getString("monitoringPointName");
            
            WorkshopMonitoringPoint monitoringPoint = new WorkshopMonitoringPoint();
            monitoringPoint.setPointName(monitoringPointName);
            monitoringPoint.setPointCode(monitoringPointName); // 使用名称作为编号
            monitoringPoint.setCompanyId(workshop.getCompanyId());
            monitoringPoint.setCompanyName(enterpriseName);
            monitoringPoint.setParkId(workshop.getParkId());
            monitoringPoint.setWorkshopId(workshop.getId());
            monitoringPoint.setWorkshopName(workshop.getWorkshopName());
            monitoringPoint.setCreateTime(LocalDateTime.now());
            monitoringPoint.setUpdateTime(LocalDateTime.now());
            monitoringPoint.setDelFlag("0");
            
            // 检查监控点是否已存在
            WorkshopMonitoringPoint existingPoint = workshopMonitoringPointService.lambdaQuery()
                    .eq(WorkshopMonitoringPoint::getPointName, monitoringPointName)
                    .eq(WorkshopMonitoringPoint::getWorkshopId, workshop.getId())
                    .one();
            
            if (existingPoint == null) {
                workshopMonitoringPointService.save(monitoringPoint);
                log.info("新增监控点：{}", monitoringPointName);
                return monitoringPoint.getId();
            } else {
                existingPoint.setPointName(monitoringPointName);
                existingPoint.setCompanyName(enterpriseName);
                existingPoint.setUpdateTime(LocalDateTime.now());
                workshopMonitoringPointService.updateById(existingPoint);
                log.info("更新监控点：{}", monitoringPointName);
                return existingPoint.getId();
            }
        } catch (Exception e) {
            log.error("保存监控点信息异常", e);
            return null;
        }
    }

    /**
     * 保存或更新企业设备信息
     */
    private void saveOrUpdateCompanyDevice(JSONObject deviceData, JSONObject enterpriseData, 
                                         JSONObject workshopData, JSONObject monitoringPointData, ComExtraWorkshop workshop, String monitoringPointId) {
        try {
            String deviceId = deviceData.getString("deviceId");
            String deviceName = deviceData.getString("deviceName");
            String deviceHardCode = deviceData.getString("deviceHardCode");
            String enterpriseId = enterpriseData.getString("enterpriseId");
            String enterpriseName = enterpriseData.getString("enterpriseName");
            String monitoringPointName = monitoringPointData.getString("monitoringPointName");
            
            CompanyDevice device = new CompanyDevice();
            device.setId(deviceId);
            device.setParkId(workshop.getParkId());
            device.setDeviceCode(deviceHardCode);
            device.setDeviceName(deviceName);
            device.setCompanyId(enterpriseId);
            device.setCompanyName(enterpriseName);
            // 在plotId中保存监控点ID，体现设备与监控点的关联关系
            device.setPlotId(monitoringPointId);
            device.setPlotName(monitoringPointName);
            device.setDoorLimitTime(10);
            device.setCreateTime(LocalDateTime.now());
            device.setUpdateTime(LocalDateTime.now());
            device.setDelFlag("0");
            
            // 检查设备是否已存在
            CompanyDevice existingDevice = companyDeviceService.getById(deviceId);
            if (existingDevice == null) {
                companyDeviceService.save(device);
                log.info("新增设备：{}，监控点：{}，监控点ID：{}", deviceName, monitoringPointName, monitoringPointId);
            } else {
                existingDevice.setDeviceName(deviceName);
                existingDevice.setDeviceCode(deviceHardCode);
                existingDevice.setCompanyName(enterpriseName);
                // 更新监控点关联
                existingDevice.setPlotId(monitoringPointId);
                existingDevice.setPlotName(monitoringPointName);
                existingDevice.setUpdateTime(LocalDateTime.now());
                companyDeviceService.updateById(existingDevice);
                log.info("更新设备：{}，监控点：{}，监控点ID：{}", deviceName, monitoringPointName, monitoringPointId);
            }
        } catch (Exception e) {
            log.error("保存企业设备信息异常", e);
        }
    }

    /**
     * 保存企业设备状态数据
     */
    private void saveCompanyDeviceStatus(JSONObject data, String deviceId) {
        try {
            JSONObject electricityRecord = data.getJSONObject("electricityRecord");
            if (electricityRecord != null) {
                CompanyDeviceStatus status = new CompanyDeviceStatus();
                status.setDeviceId(deviceId);
                status.setDataTime(LocalDateTime.parse(electricityRecord.getString("gmtModified"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                status.setLastUpdateTime(LocalDateTime.now());
                status.setCreateTime(LocalDateTime.now());
                status.setUpdateTime(LocalDateTime.now());
                status.setDelFlag("0");

                status.setChartList(data.getJSONArray("charList").toJSONString());
                // 设置电气参数
                status.setVoltageA(electricityRecord.getBigDecimal("aphaseVoltage"));
                status.setVoltageB(electricityRecord.getBigDecimal("bphaseVoltage"));
                status.setVoltageC(electricityRecord.getBigDecimal("cphaseVoltage"));
                status.setCurrentA(electricityRecord.getBigDecimal("aphaseCurrent"));
                status.setCurrentB(electricityRecord.getBigDecimal("bphaseCurrent"));
                status.setCurrentC(electricityRecord.getBigDecimal("cphaseCurrent"));
                status.setActivePower(electricityRecord.getBigDecimal("totalActivePower"));
                status.setReactivePower(electricityRecord.getBigDecimal("totalReactivePower"));
//                status.setStartStopThreshold(electricityRecord.getBigDecimal("startStopThreshold"));
                status.setPowerFactor(electricityRecord.getBigDecimal("powerFactor"));
                status.setTotalEnergy(electricityRecord.getBigDecimal("totalActiveEnergy"));
                // 根据电流判断设备状态
//                BigDecimal totalCurrent = status.getCurrentA().add(status.getCurrentB()).add(status.getCurrentC());
//                if (totalCurrent.compareTo(BigDecimal.ZERO) > 0) {
//                    status.setDeviceStatus("1"); // 运行
//                } else {
//                    status.setDeviceStatus("2"); // 停止
//                }
//
                companyDeviceStatusService.save(status);
                log.info("保存设备状态数据，设备ID：{}", deviceId);
            }
        } catch (Exception e) {
            log.error("保存企业设备状态数据异常，设备ID：{}", deviceId, e);
        }
    }

    /**
     * 保存设备数据记录
     */
    private void saveDeviceData(JSONObject data, String deviceId) {
        try {
            // 这里可以保存设备的历史数据记录
            // JSONObject electricityRecord = data.getJSONObject("electricityRecord");
            DeviceData deviceData = new DeviceData();
            deviceData.setStartStopThreshold(data.getJSONArray("deviceList").getJSONObject(0).getBigDecimal("threshold"));
            String threshold = data.getJSONArray("deviceList").getJSONObject(0).getString("threshold");
            if (threshold!=null){
                CompanyDevice companyDevice=new CompanyDevice();
                companyDevice.setId(deviceId);
                companyDevice.setStartStopThreshold(new BigDecimal(threshold));
                companyDeviceService.updateById(companyDevice);
            }
//            iDeviceDataService.updateById(deviceData);
            // 根据实际需求实现
            log.info("保存设备数据记录，设备ID：{}", deviceId);
        } catch (Exception e) {
            log.error("保存设备数据记录异常，设备ID：{}", deviceId, e);
        }
    }

    /**
     * 根据企业名称查找本地企业
     */
    private ComCompany findCompanyByName(String enterpriseName) {
        try {
            // 精确匹配
            ComCompany exactMatch = comCompanyService.lambdaQuery()
                    .eq(ComCompany::getCompanyName, enterpriseName).or(c->c.eq(ComCompany::getExtraPlatformName,enterpriseName))
                    .eq(ComCompany::getDelFlag, "0")
                    .one();
            
            if (exactMatch != null) {
                return exactMatch;
            }
            
            // 模糊匹配（去除空格、特殊字符等）
            String normalizedName = normalizeCompanyName(enterpriseName);
            List<ComCompany> companyList = comCompanyService.lambdaQuery()
                    .eq(ComCompany::getDelFlag, "0")
                    .list();
            
            for (ComCompany company : companyList) {
                String localNormalizedName = normalizeCompanyName(company.getCompanyName());
                if (normalizedName.equals(localNormalizedName)) {
                    log.info("模糊匹配成功：第三方[{}] -> 本地[{}]", enterpriseName, company.getCompanyName());
                    return company;
                }
            }
            
            return null;
        } catch (Exception e) {
            log.error("查找本地企业异常，企业名称：{}", enterpriseName, e);
            return null;
        }
    }

    /**
     * 更新企业第三方平台ID
     */
    private void updateCompanyPlatformId(ComCompany company, String platformId) {
        try {
            // 检查是否已经存在相同的第三方平台ID
            ComCompany existingCompany = comCompanyService.lambdaQuery()
                    .eq(ComCompany::getExtraPlatformId, platformId)
                    .ne(ComCompany::getId, company.getId())
                    .eq(ComCompany::getDelFlag, "0")
                    .one();
            
            if (existingCompany != null) {
                log.warn("第三方平台ID[{}]已被企业[{}]使用，跳过更新企业[{}]", 
                        platformId, existingCompany.getCompanyName(), company.getCompanyName());
                return;
            }
            
            // 更新第三方平台ID
            company.setExtraPlatformId(platformId);
            company.setUpdateTime(new java.util.Date());
            company.setUpdateBy("系统同步");
            
            boolean result = comCompanyService.updateById(company);
            if (result) {
                log.info("更新企业第三方平台ID成功：企业[{}] -> 平台ID[{}]", 
                        company.getCompanyName(), platformId);
            } else {
                log.error("更新企业第三方平台ID失败：企业[{}] -> 平台ID[{}]", 
                        company.getCompanyName(), platformId);
            }
        } catch (Exception e) {
            log.error("更新企业第三方平台ID异常，企业：{}，平台ID：{}", 
                    company.getCompanyName(), platformId, e);
        }
    }

    /**
     * 标准化企业名称（用于匹配）
     */
    private String normalizeCompanyName(String companyName) {
        if (companyName == null) {
            return "";
        }
        
        // 去除空格、特殊字符、统一大小写
        return companyName.trim()
                .replaceAll("\\s+", "")  // 去除所有空格
                .replaceAll("[（）()]", "")  // 去除括号
                .replaceAll("[有限公司|有限责任公司|股份有限公司|集团有限公司|集团|公司]", "")  // 去除公司后缀
                .replaceAll("[省|市|县|区|镇|街道|村|路|号]", "")  // 去除地址信息
                .toLowerCase();  // 转小写
    }

    /**
     * 将JSON数据转换为DeviceRelationVO对象
     */
    private DeviceRelationVO convertToDeviceRelationVO(JSONObject relationData) {
        DeviceRelationVO deviceRelation = new DeviceRelationVO();
        deviceRelation.setWorkshopName(relationData.getString("workshopName"));
        deviceRelation.setMonitoringPointName(relationData.getString("monitoringPointName"));
        
        List<JSONObject> deviceList = relationData.getJSONArray("deviceList").toJavaList(JSONObject.class);
        List<DeviceRelationVO.DeviceVO> deviceVOList = new ArrayList<>();
        
        for (JSONObject deviceData : deviceList) {
            DeviceRelationVO.DeviceVO deviceVO = new DeviceRelationVO.DeviceVO();
            deviceVO.setId(deviceData.getInteger("id"));
            deviceVO.setDeviceName(deviceData.getString("deviceName"));
            
            List<JSONObject> governanceList = deviceData.getJSONArray("governanceSiteVOList").toJavaList(JSONObject.class);
            List<DeviceRelationVO.GovernanceSiteVO> governanceVOList = new ArrayList<>();
            
            for (JSONObject governanceData : governanceList) {
                DeviceRelationVO.GovernanceSiteVO governanceVO = new DeviceRelationVO.GovernanceSiteVO();
                governanceVO.setGovernanceId(governanceData.getInteger("governanceId"));
                governanceVO.setGovernanceSiteName(governanceData.getString("governanceSiteName"));
                governanceVO.setHostStandbyType(governanceData.getInteger("hostStandbyType"));
                governanceVOList.add(governanceVO);
            }
            
            deviceVO.setGovernanceSiteVOList(governanceVOList);
            deviceVOList.add(deviceVO);
        }
        
        deviceRelation.setDeviceList(deviceVOList);
        return deviceRelation;
    }
}
